package com.tanhua.server.interceptor;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.db.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.JstlUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: tanhua
 * @description:
 * @author: MR.peng
 * @create: 2022-03-08 22:57
 **/
    /*
    *自定义拦截器
    *       1.实现接口HandlerInterceptor
    *       2.实现内部的方法
    * */
public class TokenInterceptor implements HandlerInterceptor {



    /*

    preHandle：前置方法，进入controller之前
    返回值：验证通过，进入到controller
            验证不通过，返回
      业务：判断用户请求的token，是否正确
    *
    * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头
        String token = request.getHeader("Authorization");
//        //2.判断token是否可用
//        boolean verifyToken = JwtUtils.verifyToken(token);
//        //3.如果token不可用，响应状态码401
//        if(!verifyToken){
//            response.setStatus(401);
//            return false;
//        }

        //目标：解析token，构造token对象
        //4.调用工具类，解析获取数据
        Claims claims = JwtUtils.getClaims(token);
        //5.构造User对象
        Long id = claims.get("id", Long.class);
        String mobile = claims.get("mobile", String.class);
        User user = new User();
        user.setId(id);
        user.setMobile(mobile);
        //6.存入ThreadLocal
        UserHolder.setUser(user);
        return true;
    }


    /*
    * 执行controller之后
    *
    * */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }


    /*
    *  最终(响应给前端)
    * */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
